//
//  testVC.swift
//  LeDian
//
//  Created by 三秒文化 on 16/3/17.
//  Copyright © 2016年 51ledian. All rights reserved.
//

import UIKit
import APParallaxHeader


class LDFinderMyVC: UIViewController {
    
    
    
    var cellmodel = meListCellModel()
    var model:LDUserInfoModel?
    var headview:masterViewHead?
    var headViewH:CGFloat = IPHONE6UP ? 330 : 310
    var listArr:[DDAPPConfigureModel_DesktopMe_Item] = [DDAPPConfigureModel_DesktopMe_Item]()
    var tableView:LDBaseTableView!
    
    private var dateModel:DDInterviewModel?
    dynamic var interviewCount:Int = 0
    
    
    lazy var headerViewTransImg:UIImage = {
        
        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(0))
        return image
    }()
    
    lazy var headerViewGreenImg:UIImage = {
        
        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(1))
        return image
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTabbleView()
        setupNav()
    }
    
    
    
    
    
    
    override func viewWillAppear(animated: Bool) {
        
        requestNet()
        requestInterView()
        setData()
        
        navigationController?.navigationBar.translucent = true
        navigationController?.navigationBar.setBackgroundImage(headerViewTransImg, forBarMetrics: .Default)
        navigationController?.navigationBar.shadowImage = UIImage()
        
        
    }
    
    func setData() {
        
        
        guard let appmodel = LDAPPConfigureManager.configureManger.appConfigureModel else { return }
        guard let apptype = appmodel.apptype else { return }
        
        _ = apptype.enumerate().contains { [weak self] (value) -> Bool in
            
            if value.element.id == "1-0-0" {
                
                debugPrint("version--- 1-0-0")
                self?.listArr = apptype[value.index].desktop.desktop_me.meitem ?? [DDAPPConfigureModel_DesktopMe_Item]()
                return true
            }
            
            return false
        }
        
        listArr = listArr.flatMap { (item) -> DDAPPConfigureModel_DesktopMe_Item? in
            
            if item.enable == "true" {
                
                return item
            }; return nil
        }
        
        //        debugPrint("version---",isEmployer)
        tableView.reloadData()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        
        rdv_tabBarController.setTabBarHidden(false, animated: false)
    }
    
    //    override func viewWillDisappear(animated: Bool) {
    //
    //        navigationController?.navigationBar.translucent = false
    //        navigationController?.navigationBar.setBackgroundImage(headerViewGreenImg, forBarMetrics: .Default)
    //    }
    
    func requestNet() {
        
        LDUserInfo.sharedInstance.queryUserInfo({
            [weak self] (dict) in
            
            guard let model = LDUserInfoModel.yy_modelWithDictionary(dict) else {return}
            self?.model = model
            self?.headview!.model = model
            self?.updateCellDesc()
            
        }) { (error) in
            
            LDShowHUB.shareInstance.showBarStatus(error as! String)
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(nofiCommunicationBoss), name: NotiCommunicaionCurrentJob, object: nil)
    }
    
    
    //面试列表
    
    func requestInterView() {
        
        let paramsModel = DDInterviewSendModel()
        
        paramsModel.jobfinder_id = DDLoginUserManager.userID()
        
        paramsModel.state = ""
        
        let dict = paramsModel.yy_modelToJSONObject() as?Dictionary<String,String> ?? [String:String]()
        
        LDUserInfoNet.sharedInstance.getInterviewInfoList(dict, succ: { [weak self] (dictArr) in
            
            self?.dateModel = DDInterviewModel.yy_modelWithDictionary(dictArr)
            self!.interviewCount = self?.dateModel?.count ?? 0
            
            
            if self!.interviewCount > 0 {
                
                let title = "已收到 " + "\(self!.interviewCount)" + " 个邀约面试"
                let customLabel = DDCustomLabel()
                customLabel.textColor = LDFontColor.BlackLight
                customLabel.text = title
                
                customLabel.setAttributeLabelWithtextColorPairs([["\(self!.interviewCount)":LDFontColor.Green]])
                self?.headview?.interViewLabel.attributedText = customLabel.attributedText
                self?.headview?.interViewLabel.font = UIFont.systemFontOfSize(14)
            }
            
        }) { (err) in
            
        }
    }
    
    
    
    func updateCellDesc() {
        
        //钱包1-4-1 //待面试1-4-2   //感兴趣的职位1-4-3  沟通过的Boss 1-4-4
        let newListArr = listArr.map { [weak self] (item) -> DDAPPConfigureModel_DesktopMe_Item in
            
            switch item.id {
                
            case "1-4-1":
                
                let moneybalance = self?.model?.moneybalance ?? ""
                item.desc = moneybalance
                print("jobfinder",item.id)
                return item
                
            case "1-4-2":
                
                let moneybalance = self?.model?.interviewNum ?? ""
                item.desc = moneybalance
                return item
                
            case "1-4-3":
                
                let countIntrest = self?.model?.interestedjobscount ?? ""
                item.desc = countIntrest
                return item
                
                
            case "2-4-4":
                
                let countCommun = (DDCommunicatedStore.sharedStore().communicatedBosses() ?? NSArray()).count
                item.desc = "\(countCommun)"
                return item
                
            default:
                
                return item
                
            }
        }
        
        listArr = newListArr
        self.tableView.reloadData()
        
    }
    
    func nofiCommunicationBoss() {
        
        //        let count = DDCommunicatedStore.sharedStore().communicatedBosses().count
        //        listArr[2]["rightDesc"] = "\(count)"
        //        tableView.reloadData()
    }
    
    func setTabbleView() {
        
        tableView = LDBaseTableView(frame: view.bounds)
        tableView.separatorStyle = .None
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.snp_makeConstraints { (make) in
            make.top.left.bottom.right.equalTo(0)
        }
        
        
        headview = masterViewHead(frame: CGRectMake(0, 0, LDFrame.ScreenWidth, headViewH))
        //        headview!.contentMode = UIViewContentMode.ScaleAspectFill;
        tableView?.addParallaxWithView(headview, andHeight: CGRectGetHeight(headview!.frame))
        headviewContentsClick()
    }
    
    func headviewContentsClick(){
        
        //点击头像
        headview?.sendClickHeadImg({ [weak self] in
            
            let vc = LDShowPicVC()
            vc.vcDissmiss({ [weak self] in
                
                self?.setNavTransparent()
                UIApplication.sharedApplication().statusBarHidden = false
                
                })
            
            let namelogo = self?.model?.logo ?? "default"
            vc.imgUrl = LDCommentAPI.getPicApi(namelogo)
            self?.presentViewController(vc, animated: false, completion: nil)
            
            })
        //点击微简历
        headview?.sendClickMyResume({ [weak self] in
            
            let vc = LDMyResumeViewControllerInOne()
            self?.navigationController?.pushViewController(vc, animated: true)
        })
        
        //点击投递管理
        headview?.sendClickEditMyResume({ //[weak self] in
            
            DDVerifyInfoManger().getDataVerifyClosure({ (obj) in
                
                //暂时根据 index 来确定 模块
                if obj == false {
                    
                    self.showLDAlertView("简历编辑未完成\n是否编辑?", sure: {[weak self] in
                        
                        let vc = LDMyResumeViewControllerInOne()
                        self?.navigationController?.pushViewController(vc, animated: true)
                        }, cancel: {
                            
                    })
                    
                } else {
                    
                    let vc = LDManageMyResumeVC()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
            })
        
          
//                var newArr = [Int]()
//
//                for (index,item) in arrRup.enumerate() {
//                    
//                    if item == false {
//                        
//                       newArr.append(index)
//                    }
//                }
//                var dict = [String:AnyObject]()
//                
//                //信息完整处理
//                if newArr.count == 0 {
//                    
//                    let vc = LDManageMyResumeVC()
//                    self?.navigationController?.pushViewController(vc, animated: true)
//                
//                } else {
//                    
//                    if newArr.first == 0 {
//                        
//                        dict = ["class":"LDMyResumeViewControllerInOne","notice":"个人信息未完善，请到简历编辑中完善"]
//                    } else if newArr.first == 1 {
//                        
//                        dict = ["class":"LDMyResumeViewControllerInOne","notice":"期望工作未填写，请到简历编辑中完善"]
//                    } else if newArr.first == 2 {
//                        
//                        dict = ["class":"LDMyResumeViewControllerInOne","notice":"亮点优势未填写，请到简历编辑中完善"]
//                    } else if newArr.first == 3 {
//                        
//                        dict = ["class":"LDMyResumeViewControllerInOne","notice":"工作经历未填写，请到简历编辑中完善"]
//                    } else if newArr.first == 4 {
//                        
//                        dict = ["class":"LDMyResumeViewControllerInOne","notice":"工作经历未填写，请到简历编辑中完善"]
//                    }
//                    
//                    self?.isJumpToEdit(dict)
//                }
            
        })
        
        //点击邀约面试按钮
        headview?.interViewBgView.bk_whenTapped({ [weak self] in
            
            let vc = DDInterviewListVC()
            vc.title = "我的面试邀请"
            self?.navigationController?.pushViewController(vc, animated: false)
        })
    }
    
    //判断
    func isJumpToEdit(dict:[String:AnyObject]) {
        
        let str = dict["notice"] as? String ?? "提示"
        showLDAlertView(str, sure: {[weak self] in
            
//            DDMeAdapt.push(dict)
            let vc = LDMyResumeViewControllerInOne()
            self?.navigationController?.pushViewController(vc, animated: true)
        }, cancel: {
                
        })
//        let vc = LDMyResumeViewControllerInOne()
//        navigationController?.pushViewController(vc, animated: true)
        
    }
    
    //透明
    func setNavTransparent() {
        
        navigationController?.navigationBar.setBackgroundImage(headerViewTransImg, forBarMetrics: UIBarMetrics.Default)
        navigationController?.navigationBar.shadowImage = headerViewTransImg
    }
    
    func selectIndexOfRow(index:NSIndexPath) {
        
        let className = listArr[index.row].classname
        let title = listArr[index.row].name
        
        let dict = ["class":className,"property":["title":title]]
        
        //待面试 1-4-2 处理
        if listArr[index.row].id == "1-4-2" {
            
            let vc = DDInterviewListVC()
            vc.type = .WaitInterView
            vc.title = title
            navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        //change apptype
        if listArr[index.row].id == "1-4-20" {
            
            let vc = UIApplication.sharedApplication().keyWindow?.rootViewController?.childViewControllers[0]
            DDClientInfoManager.changeClientType(vc, andShowText: "正在切换至招聘版首页")
            return
        }
        
        DDMeAdapt.push(dict as [NSObject : AnyObject])
    }
    
    /** nav设置 */
    func setupNav(){
        
        //左边 分享
        let barLeft = UIBarButtonItem(image: UIImage(named:"nav_share_white"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(self.shareBtn))
        navigationItem.leftBarButtonItem = barLeft
        
        // 设置
        let barRight = UIBarButtonItem(image: UIImage(named:"nav_setting"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(self.settingBtn))
        navigationItem.rightBarButtonItem = barRight
        navigationItem.title = ""
    }
    
    
    lazy var shareView:DDShareView = {
        
        let share = NSBundle.mainBundle().loadNibNamed("DDShareView", owner: self, options: nil).last
        
        return share as? DDShareView ?? DDShareView()
    }()
    
    func shareBtn() {
        
        //web
        let vc = LDBaseWebViewController()
        vc.reqUrl = LDShareDingDong;
        //share
        let shareBar = UIBarButtonItem().bk_initWithImage(UIImage(named: "common_nav_share"), style: .Done, handler: {
            
            [weak self](obj) in
            self?.shareView.show()
            }) as! UIBarButtonItem
        
        vc.navigationItem.rightBarButtonItem = shareBar
        navigationController?.pushViewController(vc, animated: true)
        
        
        //分享params
        let shareModel = DDShareModel()
        
        shareModel.shareTitle_SMS = kShareTitle
        shareModel.shareTitle_WeiBo = kShareTitle
        shareModel.shareTitle_WeiXin = kShareTitle
        
        shareModel.shareH5 = kShareURL
        shareModel.shareDesc = kShareContent
        
        let path = NSBundle.mainBundle().pathForResource("applogo", ofType: "png")
        shareModel.shareLogoUrl = path
        
        self.shareView.shareModel = shareModel
        
    }
    
    func settingBtn() {
        
        let vc = mySettingVC()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    //
    func setDefaultJobStatus() {
        
        LDUserInfoNet.sharedInstance.updateJobStatus("1", success: { [weak self] in
            
            LDUserInfo.sharedInstance.updataJobFinderMyResume({ (dict) in
                
//                self?.tableView?.reloadData()
            }, failure: nil)
            
            LDShowHUB.shareInstance.showBarStatus("状态更改成功")
        }) {
            
            LDShowHUB.shareInstance.showBarStatus("状态更改失败")
        }
        
    }
    
    
}
extension LDFinderMyVC {
    // MARK: - Table view data source
    
    
    
}
extension LDFinderMyVC:UITableViewDelegate,UITableViewDataSource {
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listArr.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCellWithIdentifier("cellsmy") as? meListCell
        if cell == nil {
            cell = meListCell.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cellsmy")
        }
        
        
        
        cell?.model = getCellModel(indexPath)
        return cell!
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        selectIndexOfRow(indexPath)
    }
    //MARK: -
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //        let offSetY = abs(self.tableView.contentOffset.y) // / 374
        //        let alaph = abs(374 - offSetY)*2 / 374
        //        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(alaph))
        //        self.navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: UIBarMetrics.Default)
        //        self.navigationController?.navigationBar.shadowImage = image
    }
    
    func getCellModel(indexPath:NSIndexPath)->meListCellModel {
        
        let model = meListCellModel()
        model.listName = listArr[indexPath.row].name ?? ""
        model.listPicName = listArr[indexPath.row].img ?? ""
        model.rightDesc = listArr[indexPath.row].desc ?? ""
        
        return model
    }
}
//刷新
extension LDFinderMyVC {
    
//    func initHandle() {
//        
//        //暂时根据 index 来确定 模块
//        DDVerifyInfoManger.shareManger.isAccClosue({ [weak self] (arrRup) in
//            
//            
//            if arrRup.contains(false) {
//                
//                self?.showLDAlertView("简历编辑未完成\n是否编辑?", sure: {[weak self] in
//                    
//                    let vc = LDMyResumeViewControllerInOne()
//                    self?.navigationController?.pushViewController(vc, animated: true)
//                    }, cancel: {
//                        
//                })
//                
//            } else {
//                
//                let vc = LDManageMyResumeVC()
//                self?.navigationController?.pushViewController(vc, animated: true)
//            }
//            })
//        
//    }
    
}
